#!/usr/bin/python
# -*- coding: utf-8 -*-
import cgi, cgitb
cgitb.enable()

import socket
import time
import re
t = time.time()

form = cgi.FieldStorage()

userid = form.getvalue('userid')
passwd = form.getvalue('passwd')

pcl = re.compile(r"Content-Length: (.+?)\r\n")

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("222.201.132.68",80))

def process(request):
    sock.send(request)
    head = ""
    body = ""
    body_len = 0
    while True:
        t = sock.recv(1024)
        if "\r\n\r\n" in t:
            loc = t.find("\r\n\r\n")
            head += t[:loc+2]
            body += t[loc+4:]
            break
        else:
            head += t
    m = pcl.search(head)
    body_len = int(m.group(1))
            
    while (body_len!=len(body)):
        body += sock.recv(1024)
    return head, body

get_str = """GET / HTTP/1.1
Connetion: keep-alive
HOST: jw2005.scuteo.com

"""
head, _ = process(get_str)
url = ""
for line in head.split("\r\n"):
    if line.startswith("Location"):
        url = line.split(": ")[1]
        break
urlbase = url[:-14]

get_str = """GET %s HTTP/1.1
Connetion: keep-alive
HOST: jw2005.scuteo.com

""" % url

_, body = process(get_str)
__VIEWSTATE = body.split('__VIEWSTATE" value="')[1].split('" />')[0].replace("+", "%2B")

form = "TextBox1=%s&TextBox2=%s&__VIEWSTATE=%s&RadioButtonList1=%s&Button1=&lbLanguage=" % (userid, passwd, __VIEWSTATE, "%E5%AD%A6%E7%94%9F")
post_str = """POST %s HTTP/1.1
Connetion: keep-alive
HOST: jw2005.scuteo.com
Content-Type: application/x-www-form-urlencoded
Content-Length: %d

%s
""" % (url, len(form), form)
process(post_str)
url = urlbase + "/xs_main.aspx?xh=%s" % (userid)
get_str = """GET %s HTTP/1.1
Connetion: keep-alive
HOST: jw2005.scuteo.com

""" % (url)
_, body = process(get_str)
username = body.split('"xhxm">')[1].split('</span>')[0].split("  ")[1][:-4]
url = urlbase + "/xscjcx.aspx?xh=%s&xm=%s&gnmkdm=N121605" % (userid, username)
get_str = """GET %s HTTP/1.1
Connetion: keep-alive
HOST: jw2005.scuteo.com
Referer: http://jw2005.scuteo.com

""" % (url)

_, body = process(get_str)

__VIEWSTATE = body.split('__VIEWSTATE" value="')[1].split('" />')[0].replace("+","%2B")

form = "__VIEWSTATE=%s&btn_zcj=%s" % (__VIEWSTATE, "%C0%FA%C4%EA%B3%C9%BC%A8") 
post_str = """POST %s HTTP/1.1
Connetion: keep-alive
HOST: jw2005.scuteo.com
Referer: http://jw2005.scuteo.com
Content-Type: application/x-www-form-urlencoded
Content-Length: %s

%s
""" % (url, len(form), form)
html = process(post_str)[1]
sock.close()

print "Content-Type: text/html"
print
print time.time() - t
print html
#cgi.print_environ()


